package com.scpii.universal.action;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;

import com.doone.comm.paginaction.Pagination;
import com.opensymphony.xwork2.ActionContext;
import com.scpii.universal.constant.GenericConstants;
import com.scpii.universal.dto.UserInfoDto;
import com.scpii.universal.util.EhCacheManager;
import com.scpii.universal.util.ImgAndFilePath;

/**
 * genericWeb
 * 
 * @author liuhj 2012-7-10上午11:16:50
 * @description 提供request,response,session,保存登录用户对象
 */
public class BaseAction extends PageAction implements ServletRequestAware,
		ServletResponseAware {

	private static final long serialVersionUID = 1L;
	protected HttpServletRequest request;
	protected HttpServletResponse response;
	protected HttpSession session;
	public static final String STATUS = "status";
	public static final String ERROR = "error";
	public static final String MESSAGE = "message";
	public static final String SUCCESS = "success";
	protected UserInfoDto userInfo = null;
	protected String key = null;
	protected ResourceBundle bundle = ResourceBundle.getBundle(
			GenericConstants.GLOBAL_PROPERTIES_PATH, Locale.getDefault());

	@Override
	public void setServletRequest(HttpServletRequest arg0) {
		// 使用ServletRequestAware接口通过IOC机制注入request对象
		this.request = arg0;
		session = request.getSession();
	}

	@Override
	public void setServletResponse(HttpServletResponse arg0) {
		this.response = arg0;
		response.setContentType("text/html;charset=UTF-8");
	}

	/**
	 * 设置页面不缓存
	 * 
	 * @author liuhj 2012-7-5下午04:29:44
	 */
	public void setResponseNoCache() {
		response.setHeader("progma", "no-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setHeader("Cache-Control", "no-store");
		response.setDateHeader("Expires", 0);
	}

	/**
	 * ajax信息返回
	 * 
	 * @param content
	 * @param type
	 * @return
	 * @throws IOException
	 * @author liuhj 2012-7-5下午04:33:58
	 */
	public String jsonOut(String content) throws IOException {
		setResponseNoCache();
		response.getWriter().write(content);
		response.getWriter().flush();
		response.getWriter().close();
		return null;
	}

	/**
	 * 输出json错误信息
	 * 
	 * @param message
	 * @return
	 * @throws IOException
	 * @author liuhj 2012-7-5下午04:34:18
	 */
	public String ajaxJsonErrorMessage(String message) throws IOException {
		Map<String, String> jsonMap = new HashMap<String, String>();
		jsonMap.put(STATUS, ERROR);
		jsonMap.put(MESSAGE, message);
		JSONObject jsonObject = JSONObject.fromObject(jsonMap);
		return jsonOut(jsonObject.toString());
	}

	/**
	 * http://xxxxx:8080/
	 * 
	 * @return
	 * @author liuhj 2012-7-12下午02:28:49
	 */
	protected String getServerURL() {
		// return
		// request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/";
		return (String) EhCacheManager
				.getObject(GenericConstants.SERVER_URL_PREFIX);
	}

	/**
	 * 获得tomcat部署应用的同级目录，如C:\Program Files\Tomcat 6.0\webapps\
	 * 
	 * @return
	 * @author liuhj 2012-7-12下午02:27:13
	 */
	protected String getWebAppsRealPath() {
		Boolean isDev = Boolean.valueOf(bundle.getString("is.dev"));
		String realPath = StringUtils.EMPTY;
		if (isDev) {
			realPath = ServletActionContext.getServletContext()
					.getRealPath("/");
			if (realPath.indexOf(request.getContextPath().substring(1)) != -1) {
				realPath = realPath.substring(0, realPath.lastIndexOf(request
						.getContextPath().substring(1)));
			}
		} else {
			realPath = bundle.getString("resource.root.path");
		}
		return realPath;
	}

	/**
	 * 获取图片目录基本路径,如WORKDIR\ENTERPRISE_企业ID\应用ID
	 * 
	 * @return
	 * @author liuhj 2012-7-12下午02:40:15
	 */
	protected String getImgBasePath() {
		UserInfoDto userInfo = (UserInfoDto) session
				.getAttribute(GenericConstants.USER_INFO);
		String path = ImgAndFilePath.ENTERP_WORK_DIR + "_"
				+ userInfo.getIntEnterpId() + File.separator
				+ userInfo.getAppId();
		return path;
	}

	/**
	 * 获得用户基本信息
	 * 
	 * @return
	 * @author liuhj 2012-7-12下午03:16:23
	 */
	protected UserInfoDto getUserInfo() {
		if (userInfo == null) {
			userInfo = (UserInfoDto) session
					.getAttribute(GenericConstants.USER_INFO);
		}
		return userInfo;
	}

	protected List getBatchResFromRequest(String base)
			throws FileUploadException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 设置内存缓冲区，超过后写入临时文件
		factory.setSizeThreshold(1024000000);
		// 设置临时文件存储位置
		File file = new File(base);
		if (!file.exists())
			file.mkdirs();
		factory.setRepository(file);
		ServletFileUpload upload = new ServletFileUpload(factory);
		// 设置单个文件的最大上传值
		upload.setFileSizeMax(100024000000000000l);
		// 设置整个request的最大值
		upload.setSizeMax(1000240000000000000l);
		upload.setHeaderEncoding("UTF-8");

		List items = upload.parseRequest(request);
		return items;
	}

	@Override
	public void setPageParameters(Pagination page, String strpage) {
		Map param = ActionContext.getContext().getParameters();

		if (getSelectPerPage(strpage) != -1) {
			page.setPageRecord(getSelectPerPage(strpage));
		}

		StringBuffer hidden = new StringBuffer();
		Iterator paramIt = param.keySet().iterator();
		while (paramIt.hasNext()) {
			String paramName = (String) (String) paramIt.next();
			if (paramName.equals("intCateId"))
				continue;
			String[] v = (String[]) (String[]) param.get(paramName);
			if (paramName.equals("page_currentPage_" + strpage)) {
				try {
					if (Integer.parseInt(v[0]) > page.getTotalPage()) {
						page.setCurrentPage(page.getTotalPage());
						continue;
					}
					page.setCurrentPage(Integer.parseInt(v[0]));
				} catch (Exception ex) {
					page.setCurrentPage(1);
				}
			} else {
				if (paramName.equals("page_queryflag_" + strpage)) {
					continue;
				}
				if (paramName.toLowerCase().equals("submit")) {
					continue;
				}

				if ((paramName.equals("page_currentPage_" + strpage))
						|| (paramName.equals("page_queryflag_" + strpage))
						|| (paramName.equals("page_selectPerPage_" + strpage))
						|| (paramName.equals("title" + strpage))
						|| (paramName.equals("excelcolumn" + strpage))
						|| (paramName.equals("startIndex" + strpage))
						|| (paramName.equals("method" + strpage))
						|| (paramName.equals("excelTitle" + strpage))
						|| (paramName.equals("exportMode" + strpage))
						|| (paramName.equals("queryStringInfo")))
					continue;
				for (int i = 0; i < v.length; i++) {
					String value = freemarker.template.utility.StringUtil
							.HTMLEnc(v[i]);
					hidden.append("<Input Type=\"hidden\" id=\"" + paramName
							+ "\" name=\"" + paramName + "\" value=\"" + value
							+ "\">");
				}
			}
		}
		page.setCondition(hidden.toString());
	}
}
